package com.ruoyi.web.controller.api;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysUserService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 公开API接口
 * 
 * @author ruoyi
 */
@Api(tags = "公开API接口")
@RestController
@RequestMapping("/api/public")
public class PublicApiController extends BaseController {
    
    @Autowired
    private ISysUserService userService;
    
    @Autowired
    private ISysDeptService deptService;
    
    /**
     * 获取用户信息
     */
    @ApiOperation("获取用户信息")
    @GetMapping("/user/{userId}")
    @Anonymous // 允许匿名访问，无需登录认证
    public AjaxResult getUserInfo(
            @ApiParam(value = "用户ID", required = true, example = "1")
            @PathVariable("userId") Long userId) {
        SysUser user = userService.selectUserById(userId);
        if (user != null) {
            // 出于安全考虑，不返回敏感信息
            user.setPassword(null);
            return AjaxResult.success(user);
        } else {
            return AjaxResult.error("用户不存在");
        }
    }
    
    /**
     * 获取用户列表（分页）
     */
    @ApiOperation("获取用户列表（分页）")
    @GetMapping("/users")
    @Anonymous // 允许匿名访问，无需登录认证
    public TableDataInfo getUserList() {
        startPage();
        SysUser user = new SysUser();
        List<SysUser> list = userService.selectUserList(user);
        // 移除敏感信息
        list.forEach(u -> u.setPassword(null));
        return getDataTable(list);
    }
    
    /**
     * 用户登录测试
     */
    @ApiOperation("用户登录测试")
    @PostMapping("/login")
    @Anonymous // 允许匿名访问，无需登录认证
    public AjaxResult login(@RequestBody Map<String, String> loginParams) {
        String username = loginParams.get("username");
        String password = loginParams.get("password");
        
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            return AjaxResult.error("用户名和密码不能为空");
        }
        
        // 这里仅作为API测试，实际项目中应使用正式的登录逻辑
        // 注意：这只是一个模拟的登录，不会生成真实的token
        SysUser user = new SysUser();
        user.setUserName(username);
        List<SysUser> users = userService.selectUserList(user);
        
        if (users.isEmpty()) {
            return AjaxResult.error("用户不存在");
        }
        
        Map<String, Object> data = new HashMap<>();
        data.put("userId", users.get(0).getUserId());
        data.put("username", users.get(0).getUserName());
        data.put("nickName", users.get(0).getNickName());
        data.put("deptName", users.get(0).getDept() != null ? users.get(0).getDept().getDeptName() : "");
        
        return AjaxResult.success("登录成功（测试）", data);
    }
    
    /**
     * 获取部门信息
     */
    @ApiOperation("获取部门信息")
    @GetMapping("/dept/{deptId}")
    @Anonymous // 允许匿名访问，无需登录认证
    public AjaxResult getDeptInfo(
            @ApiParam(value = "部门ID", required = true, example = "100")
            @PathVariable("deptId") Long deptId) {
        return AjaxResult.success(deptService.selectDeptById(deptId));
    }
    
    /**
     * 获取部门列表
     */
    @ApiOperation("获取部门列表")
    @GetMapping("/depts")
    @Anonymous // 允许匿名访问，无需登录认证
    public AjaxResult getDeptList() {
        return AjaxResult.success(deptService.selectDeptList(new SysDept()));
    }
    
    /**
     * 获取系统信息
     */
    @ApiOperation("获取系统信息")
    @GetMapping("/system/info")
    @Anonymous // 允许匿名访问，无需登录认证
    public AjaxResult getSystemInfo() {
        Map<String, Object> info = new HashMap<>();
        info.put("name", "RuoYi管理系统");
        info.put("version", "3.8.9");
        info.put("framework", "Spring Boot");
        info.put("database", "MySQL");
        
        return AjaxResult.success(info);
    }
}